package com.chii.user.service.impl;

import com.chii.user.mapper.UserMapper;
import com.chii.user.mapper.UserRoleRelMapper;
import com.chii.user.po.User;
import com.chii.user.po.UserRoleRel;
import com.chii.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleRelMapper userRoleRelMapper;

    @Override
    public int updateLoginTime(String username) {
        User user = userMapper.selectByName(username);
        user.setLastLoginTime(new Date());
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int insertNewUser(String username, String password, int role) {
        //存在用户着不插入
        User oldUser = userMapper.selectByName(username);
        if (oldUser != null) {
            return 0;
        }
        User user = new User();
        user.setUsername(username);
        //密码加密并且添加用户
        password = new BCryptPasswordEncoder().encode(password);
        user.setPassword(password);
        user.setCreatedAt(new Date());
        userMapper.insertSelective(user);
        //添加权限
        UserRoleRel userRoleRel = new UserRoleRel();
        userRoleRel.setRoleId(role);
        userRoleRel.setUserId(user.getId());
        UserRoleRel oldUserRoleRel = userRoleRelMapper.selectByRoleIdAndUserId(userRoleRel);
        if (oldUserRoleRel != null) {
            return 0;
        }
        userRoleRelMapper.insertSelective(userRoleRel);
        return 1;
    }

    @Override
    public User getUser(String username) {
        return userMapper.selectByName(username);
    }

    @Override
    public int insertNewRoleForUser(Integer userId,Integer roleId) {

        List<UserRoleRel> roleRels = getRoleForUser(userId);
        for (UserRoleRel roleRel : roleRels) {
            if (roleRel.getRoleId().equals(roleId)) {
                return 0;
            }
        }
        UserRoleRel userRoleRel = new UserRoleRel();
        userRoleRel.setUserId(userId);
        userRoleRel.setRoleId(roleId);
        return userRoleRelMapper.insertSelective(userRoleRel);
    }

    @Override
    public int delRoleForUser(Integer userId,Integer roleId) {
        List<UserRoleRel> roleRels = getRoleForUser(userId);
        for (UserRoleRel roleRel : roleRels) {
            if (roleRel.getRoleId().equals(roleId)) {
                return userRoleRelMapper.deleteByPrimaryKey(roleRel.getId());
            }
        }

        return 0;
    }

    @Override
    public List<UserRoleRel> getRoleForUser(Integer userId) {
        return userRoleRelMapper.selectByUserId(userId);
    }

}
